import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, Empty, Popconfirm, Table, Tag } from 'antd';

import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { DataAuthWhereTypeObj } from '@/enum/api';
import {
  roleDataPermissionDelete,
  roleDataPermissionPage
} from '@/services/base/quanxianmokuaijiaoseshujuquanxianpeizhixinxijiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import Edit, { EditRef } from './edit';

export type BizObject = BASE.RoleDataPermission;

export type DataAuthProps = {
  role?: BASE.Role;
};

const DataAuth: React.FC<DataAuthProps> = ({ role }) => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      if (!role?.id) {
        return {
          list: [],
          total: 0
        };
      }

      const res = await roleDataPermissionPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序,
        roleId: role?.id
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter,
      refreshDeps: [role]
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  if (!role) {
    return <Empty description="请选择角色" />;
  }

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                icon={<Icon icon="ri:add-fill" />}
              >
                创建数据权限
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="id">
          <SearchInput
            style={{
              width: 120 * 3
            }}
            typeList={[
              { value: 'username', children: '用户名' },
              { value: 'id', children: '用户ID' }
            ]}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      <Table<BASE.RoleDataPermission>
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '表名',
            dataIndex: 'tableName'
          },
          {
            title: '字段',
            dataIndex: 'whereField'
          },
          {
            title: '类型',
            dataIndex: 'whereType'
          },
          {
            title: '值',
            dataIndex: 'whereValue',
            width: 300
          },
          {
            title: '值类型',
            dataIndex: 'whereValueType',
            render: (v) => {
              const obj = DataAuthWhereTypeObj.get(v);

              if (!obj) {
                return emptyText;
              }

              return <Tag color={obj.color}>{obj.text}</Tag>;
            }
          },
          {
            title: 'join达式',
            dataIndex: 'expression'
          },
          {
            title: 'bean名称',
            dataIndex: 'implBeanName'
          },
          {
            title: '关联关系',
            dataIndex: 'incidenceRelation'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}

                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该角色吗？`}
                      onConfirm={async () => {
                        const res = await roleDataPermissionDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />

      <Edit ref={edit} role={role} />
    </>
  );
};

export default DataAuth;
